package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareSkuEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        /*
            skuId:
            wareId:
         */

        // wareId就是仓库的id
        String skuId = (String) params.get("skuId");
        lambdaQueryWrapper.eq(!StringUtils.isEmpty(skuId),WareSkuEntity::getSkuId,skuId);
        String wareId = (String) params.get("wareId");
        lambdaQueryWrapper.eq(!StringUtils.isEmpty(wareId),WareSkuEntity::getWareId,wareId);

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                lambdaQueryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查询sku的库存的
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map((skuId) -> {
            SkuHasStockVo vo = new SkuHasStockVo();

            // 查询数据库
            // 当前sku的总库存量
            // select SUM(stock - stock_locked) from `wms_ware_sku` where slu_id = ?
            Long count = baseMapper.getSkusStock(skuId);

            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        // 最终进行返回
        return collect;
    }

    /**
     * 完成采购后进行入库的操作
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 进行检查
        // 1.如果还没有这个库存记录的话就是新增操作
        LambdaQueryWrapper<WareSkuEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WareSkuEntity::getSkuId,skuId).eq(WareSkuEntity::getWareId,wareId);
        List<WareSkuEntity> list = list(lambdaQueryWrapper);

        if(list == null || list.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // 远程查询sku的名字
            R info = productFeignService.info(skuId);
            // TODO 远程查询sku名字，如果失败，整个事务无需要回滚
            // 自己catch掉异常
            // TODO 让异常出现以后不回滚？
            try {
                if(info.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
//                    System.out.println(data.toString());
//                    System.out.println((String) data.get("skuName"));

                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                log.error("第一次添加库存服务调用查询skuName失败{}",e);
            }
            // 添加
            baseMapper.insert(wareSkuEntity);

        } else {
            baseMapper.addStock(skuId,wareId,skuNum);
        }
    }

}